package com.zenithsun.common.basicdata.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.syzg.common.service.impl.BaseServiceImpl;
import com.syzg.common.util.SearchMap;
import com.zenithsun.common.basicdata.model.Basicdata;
import com.zenithsun.common.basicdata.service.BasicdataService;
import com.zenithsun.common.basicdata.dao.BasicdataDAO;
import com.zenithsun.common.bean.DownLoadVersion;
import com.zenithsun.common.bean.OutMessage;
import com.zenithsun.common.bean.OutMessageState;
import com.zenithsun.common.bean.TreeItem;
import com.zenithsun.common.image.StorageRule;

@Service("basicdataService")
public class BasicdataServiceImpl extends BaseServiceImpl<Basicdata> implements BasicdataService {
    
    private BasicdataDAO basicdataDAO = null;

    @Resource
	public void setbasicdataDAO(BasicdataDAO basicdataDAO) {
		this.setDAO(basicdataDAO);
		this.basicdataDAO = basicdataDAO;
	}

	@Override
	public List<TreeItem> getTreeNewsBasicData(String parentCode) throws Exception{
		List<Basicdata> nclist=null;
		if(parentCode==null||StringUtils.isEmpty(parentCode)){
			SearchMap searchMap=SearchMap.forClass(Basicdata.class);
			nclist=this.findObjects(searchMap);
		}else{
			nclist=this.basicdataDAO.getTreeNewsBasicData(parentCode);
		}
		return structureFiliation(nclist);
	}
	
	/**
	 * 构建父子关系
	 * @param nclist
	 */
	private List<TreeItem> structureFiliation(List<Basicdata> nclist){
		Map<String,TreeItem> ncmap=new HashMap<String,TreeItem>();
		Iterator<Basicdata> iter=nclist.iterator();
		//现将数据转成TreeItem存储
		while(iter.hasNext()){
			Basicdata tempBasicdata=iter.next();
			TreeItem treeItem=new TreeItem(tempBasicdata.getId(),tempBasicdata.getCode(),tempBasicdata.getComment(),tempBasicdata.getParentId());
			ncmap.put(tempBasicdata.getId(), treeItem);
		}
		return TreeItem.buildTreeItemList(ncmap);
	}

	@Override
	public DownLoadVersion getDownLoadVersion(String appType) throws Exception {
		SearchMap searchMap=SearchMap.forClass(Basicdata.class);
		searchMap.eq("a.code", appType);
		List<Basicdata> list=this.findObjects(searchMap);
		if(list!=null&&list.size()>0){
			Basicdata bd=list.get(0);
			DownLoadVersion down=new DownLoadVersion();
			down.setCode(bd.getComment());
			down.setDownLoadUrl(bd.getRemark());
			return down;
		}
		return null;
	}

	@Override
	public List<Basicdata> getBasicdataByParentCode(String parentCode) throws Exception {
		return this.basicdataDAO.getNewsBasicData(parentCode);
	}
	
	@Override
	public boolean updateApp(Basicdata basicdata) throws Exception {
		return this.basicdataDAO.updateApp(basicdata);
	}
	
	@Override
	public OutMessage uploadAppFile(String baId,String version,HttpServletRequest request) throws Exception {
		OutMessage outMessage=new OutMessage();
		// 创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		// 判断 request 是否有文件上传,即多部分请求
		if (multipartResolver.isMultipart(request)) {
			// 转换成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 取得request中的所有文件名
			Iterator<String> itr = multiRequest.getFileNames();
			if (!itr.hasNext()) {
				outMessage.setState(OutMessageState.Fail);
				return outMessage;
			}
			try {
				//加载文件存储规则
				StorageRule sr = new StorageRule(request);
				sr.setTempStore(false);
				//设置当前项目实际存储路径
				MultipartFile mpf = null;
				while (itr.hasNext()) {
					mpf = multiRequest.getFile(itr.next());
					sr.setFileName(mpf.getOriginalFilename());
					String storePath=sr.GetAppStorePath();
					File file=new File(storePath);
					//存储文件的目录是否存在，不存在则创建，否则会导致上传失败
					if(!file.getParentFile().exists()){
						file.getParentFile().mkdirs();
					}
					FileCopyUtils.copy(mpf.getBytes(),new File(storePath));
					//baId不为空，修改
					Basicdata basicdata=new Basicdata();
					basicdata.setId(baId);
					basicdata.setComment(version);
					storePath=storePath.replaceAll(sr.getCurrProjectPath()+StorageRule.appSavePath,"");
					basicdata.setRemark(storePath);
					this.updateApp(basicdata);
					outMessage.setState(OutMessageState.Success);
					outMessage.setContent((sr.GetCurrProjectPathHttpPath()+StorageRule.appSavePath+storePath).replaceAll("\\\\", "/"));
				}
			} catch (IOException e) {
				outMessage.setState(OutMessageState.Fail);
				return outMessage;
			} catch (Exception e) {
				outMessage.setState(OutMessageState.Fail);
				return outMessage;
			}
		}		
		return outMessage;
	}
}